package com.quxiu.file.service;

import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.quxiu.file.constant.FileChannel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.quxiu.common.core.utils.file.FileTypeUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * FastDFS 文件存储
 *
 * @author quxiu
 */
@Service
@ConditionalOnProperty(
        prefix = "file",
        name = {"channel"},
        havingValue = FileChannel.FDFS,
        matchIfMissing = true
)
public class FastDfsSysFileServiceImpl implements ISysFileService {

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * FastDfs文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
                FileTypeUtils.getExtension(file), null);
        return "/" + storePath.getFullPath();
    }

    @Override
    public InputStream downloadFile(String filePath) throws Exception {
        byte[] bytes = storageClient.downloadFile(StringUtils.substringBefore(filePath, "/"),
                StringUtils.substringAfter(filePath, "/"), new DownloadByteArray());
        return new ByteArrayInputStream(bytes);
    }
}
